// pages/Mall/couponDetailBuy.js
const controller= require("../controllers/Controller").controller
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    couponDetail: "",
    id: "",
    couponAccountId: "",
    shopDetail: "",
    couponBagDetail: "",
    show: false,
    isOnlyShow:false,
  },

  backindex(e){
    let page=getCurrentPages()
    let shopId=this.data.shopId
    console.log(page.length)
    if(page.length<=1){
      wx.redirectTo({
        url: '/pages/Index/Index?shopId='+shopId,
      })
    }
  },

  saveImg: function () {
    let that = this
    wx.getSetting({
      success(res) {
        //未授权 先授权 然后保存
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success(res) {
              that.saveToBlum();
            }
          })
        } else {
          //已授 直接调用保存到相册方法
          that.saveToBlum();
        }
      }
    })
  },

  saveToBlum: function () {
    let that = this
    wx.downloadFile({
      url: that.data.codeUrl,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(result) {
            wx.showToast({
              title: '保存成功',
              icon: 'success'
            })
          }
        })
      }
    })
  },

  cancle() {
    this.setData({
      show: false
    })
  },

  //获取店铺详情
  getShopDetail(id) {
    controller.shopDetails({
      shopId: id
    }).then(res => {
      this.setData({
        shopDetail: res.data
      })
    })
  },

  //获取优惠券详情
  getCouponDetail() {
    let that = this
    let shopId = wx.getStorageSync('shopId')
    let couponId = this.data.id
    let couponAccountId = this.data.couponAccountId
    if (!this.data.code&&this.data.couponAccountId) {
      controller.couponMyDetail({
        shopId: shopId,
        couponId: couponId,
        couponAccountId: couponAccountId
      }).then(res => {
        let data = res.data
        console.log("data1")
        console.log(data)
        if (data.timeState!=0&&data.effectiveEndTime&& data.effectiveStartTime) {
          data.effectiveEndTime = data.effectiveEndTime.split(" ")[0]
          data.effectiveStartTime = data.effectiveStartTime.split(" ")[0]
        }
        this.setData({
          couponDetail: data
        })
        if (!that.data.shareUserId && that.data.couponDetail.couponAccount.num > 0) {
          that.createCode()
        }
        that.getShopDetail(res.data.shopId)
      })
    } else {
      controller.shareCouponDetail({
        shopId:this.data.shopId,
        couponId: couponId,
        code:this.data.code
      }).then(res => {
        let data = res.data
        console.log("data2")
        console.log(data)
        if (data.effectiveStartTime) {
          data.effectiveEndTime = data.effectiveEndTime.split(" ")[0]
          data.effectiveStartTime = data.effectiveStartTime.split(" ")[0]
        }
        this.setData({
          couponDetail: res.data
        })
        that.getShopDetail(res.data.shopId)
        if (that.data.shareUserId && (this.data.couponDetail.couponAccount && this.data.couponDetail.couponAccount.num) > 0) {
          that.createCode()
        }
        // that.createCode()
      })
    }
  },

  toGoodsDetail(){
    wx.navigateTo({
      url: '/pages/Index/Detail?id='+this.data.couponDetail.goodsList[0].id,
    })
  },

  toUse(e) {
    let value = {}
    let that=this
    value.couponAccountId = this.data.couponAccountId
    value.couponBagId = this.data.couponBagId
    if(this.data.couponDetail.isVip){
      wx.navigateTo({
        url: '/pages/Index/Detail?id='+this.data.couponDetail.goodsList[0].id + '&couponAccountId=' + this.data.couponAccountId,
      })
    }else{
      controller.createWriteOffCouponQrCode(value).then(res => {
        this.setData({
          code: res.data.code,
          codeUrl: res.data.qrCode,
          show: true
        })
  
       if(!this.data.timer){
        this.setData({
          timer:setInterval(function(){
            let page=getCurrentPages()
            if(page[page.length-1].route!='pages/couponBagCenter/couponDetail'){
              return
            }
            that.judgeWriteOff(that)
          },6000)
        })
       }
      })
    }
  },

  toUseSecond(){
    wx.navigateTo({
      url: '/pages/Mall/Mall?couponAccountId=' + this.data.couponAccountId,
    })
  },

  //领取优惠券
  receiveCoupon() {
    let that = this
    controller.receiveCoupon({
      accountId: that.data.shareUserId,
      code: that.data.code
    }).then(res => {
      if (res.code == 1) {
        wx.showToast({
          icon: "none",
          title: '领取成功',
          duration: 1500
        })
        console.log('myCouponDetail:')
        console.log(res)
        this.setData({
          shareUserId: "",
          code: "",
          couponAccountId: res.data.id
        })
        this.getCouponDetail()

        // setTimeout(function(){
        //   wx.reLaunch({
        //     url: '/pages/Index/Detail?id='+that.data.couponDetail.goodsList[0].id,
        //   })
        // },1000)
      }
    })
  },

  //生成优惠券领取码
  createCode() {
    if(this.data.couponDetail.type==6||this.data.couponDetail.isVip==1){
      controller.createCode({
        couponAccountId: this.data.couponAccountId
      }).then(res => {
        this.setData({
          createCode: res.data
        })
      })
    }
  },

  //获取个人信息
  myInformation() {
    controller.myInformation({
      shopId: wx.getStorageSync('shopId')
    }).then(res => {
      this.setData({
        information: res.data
      })
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: options.id
      })
    }
    if (options.couponAccountId) {
      this.setData({
        couponAccountId: options.couponAccountId
      })
    }
    if (options.couponBagId) {
      this.setData({
        couponBagId: options.couponBagId
      })
    }
    if (options.out) {
      this.setData({
        out: options.out
      })
    }
    if (options.isOnlyShow) {
      this.setData({
        isOnlyShow: true
      })
    }
    if (options.code) {
      this.setData({
        code: options.code
      })
    }
    if (options.shopId) {
      this.setData({
        shopId: options.shopId
      })
      app.globalData.shopId = options.shopId
      wx.setStorageSync('shopId', options.shopId)
    }
    if (options.shareUserId) {
      this.setData({
        shareUserId: options.shareUserId
      })
    }

    this.getCouponDetail()//无需登录
    if (wx.getStorageSync('usertoken')) {
      this.myInformation()
    } else {
      app.usertokenReadyCallback = (res) => {
        this.myInformation()
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let title = this.data.couponDetail.name
    let id = this.data.id
    let code = this.data.createCode
    let shopId = wx.getStorageSync('shopId')
    console.log(shopId,'shopId');
    let shareUserId = this.data.information.id
    let couponAccountId = this.data.couponAccountId
    let couponBagId = this.data.couponBagId
    let path = "pages/Mall/couponDetailBuy?id=" + id + "&code=" + code + "&shopId=" + shopId + "&shareUserId=" + shareUserId + "&couponAccountId=" + couponAccountId + "&couponBagId=" + couponBagId
    console.log(path)

    return {
      title: title,
      path: path
    }
  }
})